import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { ListToolsRequestSchema, CallToolRequestSchema } from '@modelcontextprotocol/sdk/types.js';
import { N8nClient } from './n8n-client.js';
import dotenv from 'dotenv';

// 加载环境变量
dotenv.config();

class MCPServer {
  constructor(n8nClient) {
    this.n8nClient = n8nClient;
    
    this.server = new Server(
      {
        name: "n8n-mcp-server",
        version: "1.0.0"
      },
      {
        capabilities: {
          tools: {}
        }
      }
    );

    this.setupHandlers();
  }

  setupHandlers() {
    // 工具列表
    this.server.setRequestHandler(ListToolsRequestSchema, async () => {
      return {
        tools: [
          {
            name: "list_workflows",
            description: "获取所有N8N工作流列表",
            inputSchema: {
              type: "object",
              properties: {
                active: {
                  type: "boolean",
                  description: "是否只显示激活的工作流"
                }
              }
            }
          },
          {
            name: "create_simple_workflow",
            description: "创建简单的N8N工作流",
            inputSchema: {
              type: "object",
              properties: {
                name: {
                  type: "string",
                  description: "工作流名称"
                },
                description: {
                  type: "string", 
                  description: "工作流描述"
                }
              },
              required: ["name"]
            }
          },
          {
            name: "execute_workflow",
            description: "执行N8N工作流",
            inputSchema: {
              type: "object",
              properties: {
                workflow_id: {
                  type: "string",
                  description: "工作流ID"
                }
              },
              required: ["workflow_id"]
            }
          }
        ]
      };
    });

    // 工具调用处理
    this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
      const { name, arguments: args } = request.params;
      
      try {
        switch (name) {
          case 'list_workflows':
            return await this.handleListWorkflows(args);
          case 'create_simple_workflow':
            return await this.handleCreateSimpleWorkflow(args);
          case 'execute_workflow':
            return await this.handleExecuteWorkflow(args);
          default:
            throw new Error(`未知工具: ${name}`);
        }
      } catch (error) {
        return {
          content: [
            {
              type: "text",
              text: `❌ 错误: ${error.message}`
            }
          ],
          isError: true
        };
      }
    });
  }

  async handleListWorkflows(args) {
    const workflows = await this.n8nClient.getWorkflows(args?.active);
    
    const workflowList = workflows.map(w => 
      `📋 ${w.name} (ID: ${w.id}) - ${w.active ? '🟢 激活' : '🔴 未激活'}`
    ).join('\n');

    return {
      content: [
        {
          type: "text",
          text: `找到 ${workflows.length} 个工作流:\n\n${workflowList || '暂无工作流'}`
        }
      ]
    };
  }

  async handleCreateSimpleWorkflow(args) {
    const { name, description } = args;
    
    const workflowTemplate = {
      name,
      nodes: [
        {
          id: 'start',
          name: 'When clicking Test workflow',
          type: 'n8n-nodes-base.manualTrigger',
          typeVersion: 1,
          position: [240, 300],
          parameters: {}
        },
        {
          id: 'set',
          name: 'Set',
          type: 'n8n-nodes-base.set',
          typeVersion: 1,
          position: [460, 300],
          parameters: {
            values: {
              string: [
                {
                  name: 'message',
                  value: `Hello from ${name}!`
                },
                {
                  name: 'description',
                  value: description || 'Created via MCP'
                }
              ]
            }
          }
        }
      ],
      connections: {
        'When clicking Test workflow': {
          main: [
            [
              {
                node: 'Set',
                type: 'main',
                index: 0
              }
            ]
          ]
        }
      },
      active: false
    };
    
    const newWorkflow = await this.n8nClient.createWorkflow(workflowTemplate);
    
    return {
      content: [
        {
          type: "text",
          text: `✅ 工作流创建成功!\n\n📋 名称: ${newWorkflow.name}\n🆔 ID: ${newWorkflow.id}\n📝 描述: ${description || '无描述'}`
        }
      ]
    };
  }

  async handleExecuteWorkflow(args) {
    const { workflow_id } = args;
    
    const execution = await this.n8nClient.executeWorkflow(workflow_id);
    
    return {
      content: [
        {
          type: "text",
          text: `🚀 工作流执行成功!\n\n🆔 执行ID: ${execution.id}\n📊 状态: ${execution.status}`
        }
      ]
    };
  }

  async start() {
    const transport = new StdioServerTransport();
    await this.server.connect(transport);
    console.error('🚀 N8N MCP服务器已启动 (stdio模式)');
    
    // 保持进程运行
    process.stdin.resume();
  }
}

// 主函数：创建并启动MCP服务器
async function main() {
  try {
    console.error('🚀 启动N8N MCP服务器...');
    
    // 创建N8N客户端
    const n8nClient = new N8nClient(
      process.env.N8N_BASE_URL || 'http://localhost:5678',
      process.env.N8N_API_KEY
    );

    // 测试N8N连接
    console.error('🔍 测试N8N连接...');
    const connectionTest = await n8nClient.testConnection();
    
    if (!connectionTest.success) {
      console.error('❌ N8N连接失败:', connectionTest.message);
      console.error('💡 请确保N8N正在运行: npx n8n start');
      console.error('⚠️  MCP服务器将继续启动，但N8N功能将不可用');
    } else {
      console.error('✅ N8N连接成功');
    }

    // 创建并启动MCP服务器
    console.error('📡 启动MCP服务器...');
    const mcpServer = new MCPServer(n8nClient);
    await mcpServer.start();
    
    console.error('✅ MCP服务器已准备就绪，等待客户端连接...');
    
  } catch (error) {
    console.error('❌ 启动失败:', error.message);
    console.error('错误详情:', error.stack);
    process.exit(1);
  }
}

// 如果直接运行此文件，启动服务器
if (import.meta.url === `file:///${process.argv[1].replace(/\\/g, '/')}`) {
  main();
}

export { MCPServer };